package cn.zt.ztzx.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.zt.ztzx.domain.SysUser;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.concurrent.TimeUnit;


@Component
public class MyHandler  implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    //prehandler：在请求处理之前进行调用（Controller方法调用之前）
    //true： 放行，false：拦截
    @Override

    //只有经过登录认证的才允许放行，否则直接拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器执行了prehandle");
        //options请求： 跨域预检请求，一般要予以放行
        if ("OPTIONS".equals(request.getMethod())){
            return true;
        }

        //请求方法： get  post  delete  put trace  options  header
//        String requestURI = request.getRequestURI();
      /*  if (requestURI.contains("login")){
            return false;
        }*/

        //获取token进行解析 ,从请求头中获取token
        String token = request.getHeader("token");
        if (StrUtil.isEmpty(token)){

            return false;
        }
        //从redis中取出用户信息进行对比
        String s = redisTemplate.opsForValue().get("user:login:" + token);
        if (StrUtil.isEmpty(s)){
            return false;
        }
        SysUser sysUser = JSON.parseObject(s, SysUser.class);
        if (ObjectUtil.isEmpty(sysUser)){
            return false;
        }
        //延长token的有效时长
        redisTemplate.opsForValue().set("user:login:"+token,s,30, TimeUnit.MINUTES);
        return  true;
    }

    //postHandler：请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器执行了postHandle方法");
    }

    //afterCompletion：在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("拦截器执行了afterCompletion方法");
    }
}